<?php

namespace addons\facrm\controller\facrm\analysis;

use addons\facrm\library\BackendApi;
use app\admin\model\AuthGroup;
use app\common\controller\Backend;
use fast\Date;
use fast\Tree;
use think\Db;
use function fast\e;


/**
 * 排行榜
 */
class Ranking extends BackendApi
{
    protected $model = null;
    protected $searchFields = 'id,username,nickname';
    protected $groupList = [];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('app\admin\model\Admin');

        $this->childrenAdminIds = $this->auth->getChildrenAdminIds(true);
        $this->childrenGroupIds = $this->auth->getChildrenGroupIds(true);
        $this->groupList = $groupList = collection(AuthGroup::where('id', 'in', $this->childrenGroupIds)->select())->toArray();
        Tree::instance()->init($groupList);
        $this->request->filter(['strip_tags']);

    }

    /**
     * 合同排行
     */
    public function contract()
    {
        $contractModel = new \app\admin\model\facrm\Contract();

        $filter = $this->request->get("filter", '');
        $filter = (array)json_decode($filter, true);
        $filter_c = [];
        if (isset($filter['search_time'])) {
            $filter['search_time'] = str_replace(' - ', ',', $filter['search_time']);
            $arr = array_slice(explode(',', $filter['search_time']), 0, 2);
            if (count($arr)<2)return $this->error(__("时间参数有误"));

            $filter_c['order_time'] = ['between time', $arr];
        }else{
            //本月
            $thismonth_start= Date::unixtime('month');
            $thismonth_end = Date::unixtime('month', 0, $position = 'end');
            $filter_c['order_time'] = ['between time', [$thismonth_start,$thismonth_end]];
        }

        $childrenAdminIds =$this->getChildrenAdminIds($filter);
        if ($childrenAdminIds){
            $contractModel->where('order_admin_id', 'in', $childrenAdminIds);
        }

        $order = "money";
        if (isset($filter['type_id'])) {
            switch ($filter['type_id']) {
                case 1:
                    $order = "count";
                    break;
                case 2:
                    $order = "money";
                    break;
            }
        }

        $lists = $contractModel->where('check_status', 2)->where($filter_c)
            ->field('COUNT(*) AS count, sum(money) as money,order_admin_id')
            ->group('order_admin_id')->limit(0, 10)->order($order, 'desc')->fetchSql(false)
            ->select();
        $j = 1;
        foreach ($lists as $row) {
            // $row->orderAdmin;
            if ($row->orderAdmin){
                $row->orderAdmin->hidden(['password', 'token', 'salt']);
                $row->orderAdmin->groups = $this->auth->getGroups($row->orderAdmin->id);
            }
            $row['index'] = $j;
            $j++;
        }
        $result = array("total" => count($lists), "rows" => $lists);
        $this->success('',$result);
    }

    /**
     * 回款排行
     */
    public function receivables()
    {
        $receivablesModel = new \app\admin\model\facrm\contract\Receivables();

        $filter = $this->request->get("filter", '');
        $filter = (array)json_decode($filter, true);
        $filter_c = [];
        if (isset($filter['search_time'])) {
            $filter['search_time'] = str_replace(' - ', ',', $filter['search_time']);
            $arr = array_slice(explode(',', $filter['search_time']), 0, 2);
            if (count($arr)<2)return $this->error(__("时间参数有误"));
            $filter_c['return_time'] = ['between time', $arr];
        }

        $childrenAdminIds =$this->getChildrenAdminIds($filter);
        if ($childrenAdminIds){
            $receivablesModel->where('order_admin_id', 'in', $childrenAdminIds);
        }

        $order = "money";
        if (isset($filter['type_id'])) {
            switch ($filter['type_id']) {
                case 1:
                    $order = "count";
                    break;
                case 2:
                    $order = "money";
                    break;
            }
        }

        $lists = $receivablesModel->where('check_status', 2)->where($filter_c)
            ->field('COUNT(*) AS count, sum(money) as money,order_admin_id')
            ->group('order_admin_id')->limit(0, 10)->order($order, 'desc')->fetchSql(false)
            ->select();
        $j = 1;
        foreach ($lists as $row) {
            if ($row->orderAdmin){
                $row->orderAdmin->hidden(['password', 'token', 'salt']);
                $row->orderAdmin->groups = $this->auth->getGroups($row->orderAdmin->id);
            }
            $row['index'] = $j;
            $j++;
        }
        $result = array("total" => count($lists), "rows" => $lists);

        $this->success('',$result);
    }

    /**
     * 新客排名
     * @return string|\think\response\Json|void
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function addCustomer()
    {
        $customerModel = new \app\admin\model\facrm\Customer();

        $filter = $this->request->get("filter", '');
        $filter = (array)json_decode($filter, true);
        $filter_c = [];
        if (isset($filter['search_time'])) {
            $filter['search_time'] = str_replace(' - ', ',', $filter['search_time']);
            $arr = array_slice(explode(',', $filter['search_time']), 0, 2);
            if (count($arr)<2)return $this->error(__("时间参数有误"));
            $filter_c['create_time'] = ['between time', $arr];
        }

        $childrenAdminIds =$this->getChildrenAdminIds($filter);
        if ($childrenAdminIds){
            $customerModel->where('create_user_id', 'in', $childrenAdminIds);
        }

        $order = "count";
        $lists = $customerModel->where($filter_c)
            ->field('COUNT(*) AS count,create_user_id')
            ->group('create_user_id')->limit(0, 10)->order($order, 'desc')->fetchSql(false)
            ->select();
        $j = 1;
        foreach ($lists as $row) {
            // $row->orderAdmin;
            if ($row->createUser){
                $row->createUser->hidden(['password', 'token', 'salt']);
            }
            $row['index'] = $j;
            $j++;
        }
        $result = array("total" => count($lists), "rows" => $lists);

        $this->success('',$result);
    }

    /**
     * 跟进排名
     */
    public function record()
    {
        $recordModel = new \app\admin\model\facrm\Record();

        $filter = $this->request->get("filter", '');
        $filter = (array)json_decode($filter, true);
        $filter_c = [];
        if (isset($filter['search_time'])) {
            $filter['search_time'] = str_replace(' - ', ',', $filter['search_time']);
            $arr = array_slice(explode(',', $filter['search_time']), 0, 2);
            if (count($arr)<2)return $this->error(__("时间参数有误"));

            $filter_c['create_time'] = ['between time', $arr];
        }
        $childrenAdminIds =$this->getChildrenAdminIds($filter);
        if ($childrenAdminIds){
            $recordModel->where('create_user_id', 'in', $childrenAdminIds);
        }
        $order = "count";
        $filter['type_id'] = isset($filter['type_id']) ? $filter['type_id'] : 1;
        switch ($filter['type_id']) {
            case 1:
                $order = "count";//跟进次数
                break;
            case 2:
                $order = "total";//客户数量select create_user_id, count(distinct types_id) as count,count(*) as aa from fa_facrm_record group by create_user_id ORDER BY count desc  LIMIT 0,10
                break;
            default:
                return $this->error(__("访问有误"));
        }
        $lists = $recordModel->where('types', "customer")->where($filter_c)
            ->field("count(distinct types_id) AS total,create_user_id,types_id,count(*) as count")
            ->group('create_user_id')->limit(0, 10)->order($order, 'desc')->fetchSql(false)
            ->select();
        $j = 1;
        foreach ($lists as $row) {
            $row->createUser->hidden(['password', 'token', 'salt']);
            $row['index'] = $j;
            $j++;
        }

        $result = array("total" => count($lists), "rows" => $lists);

        $this->success('',$result);
    }

    /**
     * 产品排名
     * @return \think\response\Json|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function product()
    {
        $productModel = new \app\admin\model\facrm\contract\Product();
        $productModel->alias('p')->join('facrm_contract c','c.id=p.contract_id');
        $filter = $this->request->get("filter", '');
        $filter = (array)json_decode($filter, true);
        $filter_c = [];
        if (isset($filter['search_time'])) {
            $filter['search_time'] = str_replace(' - ', ',', $filter['search_time']);
            $arr = array_slice(explode(',', $filter['search_time']), 0, 2);
            if (count($arr)<2)return $this->error(__("时间参数有误"));
            $start_time=strtotime($arr[0]);
            $end_time=strtotime($arr[1]);
            $productModel->where("c.order_time BETWEEN {$start_time} AND {$end_time}");

        }
        $childrenAdminIds =$this->getChildrenAdminIds($filter);
        if ($childrenAdminIds){
            $productModel->where('order_admin_id', 'in', $childrenAdminIds);
        }
        $order = "count";
        $filter['type_id'] = isset($filter['type_id']) ? $filter['type_id'] : 1;
        switch ($filter['type_id']) {
            case 1:
                $order = "count";//销售数量
                break;
            case 2:
                $order = "total";//销售金额
                break;
            default:
                return $this->error(__("访问有误"));
        }
        $lists = $productModel->where('check_status',2)
            ->field("count(*) as count,sum(subtotal) as total,product_id,p.name,product_id")
            ->limit(0, 10)->order($order, 'desc')->fetchSql(false)->group('product_id')
            ->select();
        $j = 1;
        foreach ($lists as $row) {
            $row['index'] = $j;
            $j++;
        }

        $result = array("total" => count($lists), "rows" => $lists);

        $this->success('',$result);
    }

    protected function getChildrenAdminIds($filter)
    {
        $childrenAdminIds = [];
        if (isset($filter['group_id'])) {
            $childrenAdminIds = [];
            if ($filter['group_id'] > 0) {
                Tree::instance()->init($this->groupList);
                $groupIds = Tree::instance()->getChildrenIds($filter['group_id'], true);

                $authGroupList = \app\admin\model\AuthGroupAccess::
                field('uid,group_id')
                    ->where('group_id', 'in', $groupIds)
                    ->select();
                foreach ($authGroupList as $k => $v) {
                    if (in_array($v['uid'], $childrenAdminIds)) continue;
                    $childrenAdminIds[] = $v['uid'];
                }
                if (!$childrenAdminIds) {

                    return $this->error("该组下面没有成员");
                }
            }
        }
        return  $childrenAdminIds;
    }

}
